package com.hmdp.utils;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.BooleanUtil;
import lombok.AllArgsConstructor;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName SimpleRedisLock
 * @Description TODO
 * @Author kiku
 * @Date 2025/2/10 14:48
 * @Version 1.0
 */
@Component
@Data
public class SimpleRedisLock implements ILock {
    private String name;
    @Autowired
    private StringRedisTemplate redisTemplate;


    private static final String KEY_PREFIX = "lock:";
    private static final String ID_PREFIX = UUID.randomUUID().toString(true) + "-";
    private static final DefaultRedisScript<Long> unlockScript;

    static {
        unlockScript = new DefaultRedisScript<>();
        unlockScript.setLocation(new ClassPathResource("unlock.lua"));
        unlockScript.setResultType(Long.class);
    }

    @Override
    public boolean tryLock(long timeout) {
        //线程标识,保证自己释放自己的锁
        String id = ID_PREFIX + Thread.currentThread().getId();
        Boolean success = redisTemplate.opsForValue().
                setIfAbsent(KEY_PREFIX + name, id, timeout, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(success);
    }


    @Override
    public void unlock() {
        //调用lua脚本
        redisTemplate.execute(unlockScript,
                Collections.singletonList(KEY_PREFIX + name),
                ID_PREFIX + Thread.currentThread().getId()
        );


    }
//    @Override
//    public void unlock() {
//        //判断线程标识
//        String threadId=ID_PREFIX+Thread.currentThread().getId();
//        String id = redisTemplate.opsForValue().get(KEY_PREFIX + name);
//        if (threadId.equals(id)){
//            //释放锁
//            redisTemplate.delete(KEY_PREFIX + name);
//        }
//
//    }
}
